#region Copyright (c) 2003, newtelligence AG. All rights reserved.

/*
// Copyright (c) 2003, newtelligence AG. (http://www.newtelligence.com)
// Original BlogX Source Code: Copyright (c) 2003, Chris Anderson (http://simplegeek.com)
// All rights reserved.
//  
// Redistribution and use in source and binary forms, with or without modification, are permitted 
// provided that the following conditions are met: 
//  
// (1) Redistributions of source code must retain the above copyright notice, this list of 
// conditions and the following disclaimer. 
// (2) Redistributions in binary form must reproduce the above copyright notice, this list of 
// conditions and the following disclaimer in the documentation and/or other materials 
// provided with the distribution. 
// (3) Neither the name of the newtelligence AG nor the names of its contributors may be used 
// to endorse or promote products derived from this software without specific prior 
// written permission.
//      
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 
// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 
// AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER 
// IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 
// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// -------------------------------------------------------------------------
//
// Original BlogX source code (c) 2003 by Chris Anderson (http://simplegeek.com)
// 
// newtelligence is a registered trademark of newtelligence Aktiengesellschaft.
// 
// For portions of this software, the some additional copyright notices may apply 
// which can either be found in the license.txt file included in the source distribution
// or following this notice. 
//
*/

#endregion

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace newtelligence.DasBlog.Web.Core.Macros
{
    /// <summary>
    /// This class provides a compatible implementation of the 
    /// macros available in Userland's Radio application.
    /// </summary>
    public class RadioMacros
    {
        protected SharedBasePage requestPage;

        /// <summary>
        /// RadioMacros' constructor
        /// </summary>
        /// <param name="page">The page we are rendering.</param>
        public RadioMacros(SharedBasePage page)
        {
            requestPage = page;
        }

        // TODO: Documentation for args

        // TODO: Documentation for args

        /// <summary>
        /// This macro renders an OPML outline. The outline is displayed as an
        /// hierarchical list. Each item with subitems is displayed with an icon
        /// on the left hand side. The default image is "images/outlinearrow.gif" for
        /// the collapsed state and "images/outlinedown.gif" for the expanded state.
        /// Both file names are relative to the site root. Each item without subitems
        /// is rendered with an RSS icon on the left hand side. The image used is
        /// "images/xmlButton.gif". 
        /// </summary>
        /// <param name="url">Absolute URL to the outline or relative local path</param>
        /// <returns></returns>
        /// <remarks>
        /// Renders a complex control with the following CSS styles:<br />
        /// <table>
        ///    <tr><td>Outermost container (&lt;div&gt;)<td></td>blogRollContainerStyle</td></tr>
        ///    <tr><td>Contained table (&lt;table&gt;)<td></td>blogRollTableStyle</td></tr>
        ///    <tr><td>Table cells (&lt;td&gt;)<td></td>blogRollCellStyle</td></tr>
        ///    <tr><td>RSS Hyperlink (&lt;a&gt;)<td></td>blogRollXmlLinkStyle</td></tr>
        ///    <tr><td>Text Hyperlink (&lt;div&gt;)<td></td>blogRollLinkStyle</td></tr>
        ///    <tr><td>Nested outline header table (&lt;table&gt;)<td></td>blogRollNestedOutlineHeaderTableStyle</td></tr>
        ///    <tr><td>Collapsed nested outline (&lt;div&gt;)<td></td>blogRollCollapsed (this must be changed in or removed from "scripts/outline.css" to override the default)</td></tr>
        ///    <tr><td>Expanded nested outline (&lt;div&gt;)<td></td>blogRollExpanded (this must be changed in or removed from "scripts/outline.css" to override the default)</td></tr>
        ///    <tr><td>Nested outline header image cell (&lt;td&gt;)<td></td>blogRollNestedOutlineBadgeCellStyle</td></tr>
        ///    <tr><td>Nested outline header text cell (&lt;td&gt;)<td></td>blogRollNestedOutlineTitleCellStyle</td></tr>
        ///    <tr><td>Nested outline header image link (&lt;a&gt;)<td></td>blogRollNestedOutlineBadgeStyle</td></tr>
        ///    <tr><td>Nested outline header image link (&lt;a&gt;)<td></td>blogRollNestedOutlineTitleStyle</td></tr>
        ///    <tr><td>Nested outline header image cell (&lt;td&gt;)<td></td>blogRollNestedOutlineBadgeStyle</td></tr>
        ///    <tr><td>Nested outline body table (&lt;table&gt;)<td></td>blogRollNestedOutlineBodyTableStyle (sub-elements repeat with above styles)</td></tr>
        /// </table>
        /// </remarks>
        public virtual Control BlogRoll(string url)
        {
            SideBarOpmlList list = new SideBarOpmlList();
            list.FileName = url;
            list.RenderDescription = requestPage.SiteConfig.EnableBlogrollDescription;
            return list;
        }

        /// <summary>
        /// Renders the time of the last site update, expressed in GMT
        /// </summary>
        /// <returns></returns>
        /// <remarks>Renders plans text</remarks>
        public virtual Control GetLastUpdate()
        {
            if (requestPage.SiteConfig.AdjustDisplayTimeZone)
            {
                return
                    new LiteralControl(
                        requestPage.SiteConfig.GetConfiguredTimeZone().FormatAdjustedUniversalTime(
                            requestPage.DataService.GetLastEntryUpdate()));
            }
            else
            {
                return new LiteralControl(requestPage.DataService.GetLastEntryUpdate().ToString("U") + " UTC");
            }
        }

        /// <summary>
        /// Renders a search hyperlink, pointing to Google.com. The search expression
        /// is the title as passed the macro.
        /// </summary>
        /// <param name="title"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public virtual Control GoogleIt(string title, params string[] args)
        {
            HyperLink xmlLink = new HyperLink();
            xmlLink.NavigateUrl = "http://www.google.com/search?q=" + HttpUtility.UrlEncode(title);

            if (args != null && args.Length == 1)
            {
                xmlLink.Text = args[0];
            }
            else
            {
                xmlLink.Text = "GoogleIt";
            }

            return xmlLink;
        }

        /// <summary>
        /// This macro renders a set of &lt;link&gt; and &lt;meta&gt; tags
        /// for including in the &lt;head&gt; section of the page. 
        /// </summary>
        /// <returns></returns>
        [Obsolete]
        public virtual Control HeadLinks()
        {
            PlaceHolder placeHolder = new PlaceHolder();
            return placeHolder;
        }

        /// <summary>
        /// Ignored in this version.
        /// </summary>
        /// <returns>Renders nothing</returns>
        public virtual Control EditThisPageButton()
        {
            return new LiteralControl("");
        }

        /// <summary>
        /// Renders the administrator bar, if the user is logged and is member
        /// of the "admin" role.
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public virtual Control EditorsOnlyMenu(params string[] args)
        {
            // Load the admin bar if we have a valid contributor - the control itself
            // will handle what is visible for the type of role.
            if ((!requestPage.HideAdminTools) && SiteSecurity.IsValidContributor())
            {
                return requestPage.LoadControl("AdminNavBar.ascx");
            }
            else
            {
                return new LiteralControl("");
            }
        }

        /// <summary>
        /// Returns an absolute URL to an image based on a partial URL 
        /// relative to the Radio system path. 
        /// </summary>
        /// <param name="img">Relative URL to image.</param>
        /// <param name="args"></param>
        /// <returns></returns>
        /// <remarks>
        /// Renders one &lt;img&gt; tag with CSS class "simpleImageStyle"
        /// </remarks>
        public virtual Control ImageRef(string img, params string[] args)
        {
            Image imgCtl = new Image();
            imgCtl.CssClass = "simpleImageStyle";
            imgCtl.ImageUrl =
                new Uri(new Uri(SiteUtilities.GetBaseUrl(requestPage.SiteConfig)), requestPage.BlogTheme.ImageDirectory) +
                "/" + img;
            return imgCtl;
        }

        /// <summary>
        /// Returns an absolute URL to an image based on a partial URL 
        /// contained in a design template.
        /// </summary>
        /// <param name="img">Relative URL to image.</param>
        /// <returns></returns>
        public virtual Control ImageUrl(string img)
        {
            return new LiteralControl(new Uri(new Uri(SiteUtilities.GetBaseUrl(requestPage.SiteConfig)),
                                              requestPage.BlogTheme.ImageDirectory) + "/" + img);
        }

        /// <summary>
        /// Returns an absolute URL to an image based on a partial URL 
        /// contained in a design template.
        /// </summary>
        /// <param name="img">Relative URL to image.</param>
        /// <param name="args"></param>
        /// <returns></returns>
        public virtual Control ImageUrl(string img, params string[] args)
        {
            return
                new LiteralControl(
                    new Uri(new Uri(SiteUtilities.GetBaseUrl(requestPage.SiteConfig)),
                            requestPage.BlogTheme.ImageDirectory) + "/" + img);
        }

        /// <summary>
        /// Generates a link to the author's email address or some page
        /// providing feedback capability. If SiteConfig.ObfuscateEmail is enabled this
        /// address will be Obfuscated.
        /// </summary>
        /// <returns></returns>
        /// <remarks>Renders one &lt;a&gt; tag with the CSS class "mailToStyle" and 
        /// an embedded &lt;img&gt; tage with the CSS class "mailToImageStyle"</remarks>
        public virtual Control MailTo()
        {
            HyperLink xmlLink = new HyperLink();
            xmlLink.CssClass = "mailToStyle";

            string messageSubject = (requestPage.TitleOverride != null && requestPage.TitleOverride.Length > 0)
                                        ? requestPage.SiteConfig.Title + " - " + requestPage.TitleOverride
                                        : requestPage.SiteConfig.Title;
            messageSubject = messageSubject.Replace("'", @"\'");
            string emailAddress = requestPage.SiteConfig.Contact;

            if (requestPage.SiteConfig.ObfuscateEmail)
            {
                xmlLink.NavigateUrl = SiteUtilities.GetObfuscatedEmailUrl(emailAddress, messageSubject);
            }
            else
            {
                xmlLink.NavigateUrl =
                    String.Format("mailto:{0}?Subject={1}", requestPage.SiteConfig.Contact, messageSubject);
            }

            Image img = new Image();
            img.CssClass = "mailToImageStyle";
            img.ToolTip = img.AlternateText = SharedBasePage.CoreStringTables.GetString("text_send_mail");
            img.ImageUrl = requestPage.GetThemedImageUrl("mailTo");
            xmlLink.Controls.Add(img);

            return xmlLink;
        }

        /// <summary>
        /// Unused, provided for backwards template-compatibility with Radio Userland only
        /// </summary>
        /// <returns></returns>
        public virtual Control StaticSiteStatsImage()
        {
            return new LiteralControl("");
        }

        /// <summary>
        /// The URL of this weblog.
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        /// <remarks>Renders plain text</remarks>
        public virtual Control WeblogUrl(params string[] args)
        {
            return new LiteralControl(SiteUtilities.GetStartPageUrl(requestPage.SiteConfig));
        }

        /// <summary>
        /// Generates a text link to the (equivalent of) the Radio coffee mug.
        /// </summary>
        /// <returns></returns>
        /// <remarks>
        /// Renders one &lt;a&gt; tag with the CSS class "xmlCoffeeMugStyle"
        /// </remarks>
        public virtual Control XmlCoffeeMug()
        {
            HyperLink xmlLink = new HyperLink();
            xmlLink.CssClass = "xmlCoffeeMugStyle";
            xmlLink.NavigateUrl = "http://127.0.0.1:5335/system/pages/subscriptions?url=" + SiteUtilities.GetRssUrl();
            xmlLink.Target = "";
            Image img = new Image();
            img.CssClass = "xmlCoffeeMugImageStyle";
            img.ImageUrl = requestPage.GetThemedImageUrl("xmlCoffeeMug");
            img.ToolTip = img.AlternateText = SharedBasePage.CoreStringTables.GetString("text_subscribe");
            xmlLink.Controls.Add(img);

            return xmlLink;
        }
    }
}